package com.hong.springboot.netty;

import com.hong.springboot.dao.UserMapper;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author: csh
 * @Date: 2021/1/19 11:45
 * @Description:WebSocket服务器使用独立的线程启动
 */
@Log4j2
@Component
public class WebsocketServer {

    @Autowired
    private UserMapper userMapper;

    private ChannelFuture serverChannelFuture;

    private  EventLoopGroup bossGroup;

    private  EventLoopGroup workerGroup;
    @Value("${websocket.server.port}")
    private int port;


    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     *
     * 功能描述: websocket服务器
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/1/19 11:45
     */
    @PostConstruct
    public void start() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            System.out.println("websocket启动了！");
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebsocketChannelInitializer(userMapper));
            serverChannelFuture = serverBootstrap.bind(port).sync();
            log.info("springboot websockt服务启动完成，已绑定端口： " + port);
        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.error("springboot websocket服务启动异常！", e);
        }
    }
    /**
     *
     * 功能描述: 关闭Netty Websocket服务器，主要是释放连接
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/1/19 11:48
     */
    @Deprecated
    public void close() {
        serverChannelFuture.channel().close();
        Future<?> bossGroupFuture = bossGroup.shutdownGracefully();
        Future<?> workerGroupFuture = workerGroup.shutdownGracefully();

        try {
            bossGroupFuture.await();
            workerGroupFuture.await();
            log.info("springboot websocket服务停止中...");
        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
        }
    }
}
